using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

using MWC.BL;

using BugSense;

namespace MWC.NetcampCheckin
{
    [Activity(Label = "Netcamp Choose Email")]
    public class NetcampChooseEmail : Activity
    {
        bool tryForTheSecondTime = true;
        Meeting meeting;
        
        NetcampWebProxy.WebProxy proxy = new NetcampWebProxy.WebProxy();

  
        protected override void OnCreate(Bundle bundle)
        {
            try
            {
                base.OnCreate(bundle);

                proxy.Proxy = null;

                BugSenseHandler.Instance.ClearCrashExtraData();
                BugSense.Core.Model.LimitedCrashExtraDataList extras = BugSenseHandler.Instance.CrashExtraData;

                extras.Add(new BugSense.Core.Model.CrashExtraData
                {
                    Key = "Screen",
                    Value = "NetcampChooseEmail"
                });

                tryForTheSecondTime = true;

                //String[] lol = {"zeddq1@gmail.com", "dwa"};
                String[] emails = Intent.GetStringArrayExtra("emails");

                SetContentView(Resource.Layout.NetcampChooseEmail);

                List<TextView> listBold = new List<TextView>();
                listBold.Add(FindViewById<TextView>(Resource.Id.firstParenthasesOfTitle));
                listBold.Add(FindViewById<TextView>(Resource.Id.secondParanthasesOfTitle));
                listBold.Add(FindViewById<TextView>(Resource.Id.boldTextOfSubtitle));
                listBold.Add(FindViewById<TextView>(Resource.Id.boldTextOfTitle));
                setFont("fonts/texgyreheros-regular-webfont.ttf", listBold, TypefaceStyle.Bold);


                List<TextView> listNormal = new List<TextView>();
                listNormal.Add(FindViewById<TextView>(Resource.Id.normalTextOfTitle));
                listNormal.Add(FindViewById<TextView>(Resource.Id.normalTextOfSubtitle));
                listNormal.Add(FindViewById<TextView>(Resource.Id.setMail));

                setFont("fonts/texgyreheros-regular-webfont.ttf", listNormal, TypefaceStyle.Normal);

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, Resource.Layout.EmailListItem, emails);
                ListView emailListView = FindViewById<ListView>(Resource.Id.EmailListView);
                if (emailListView != null && adapter != null)
                    emailListView.Adapter = adapter;

                if (emailListView == null)
                    Console.WriteLine("yyy emailListView jest nullem");
                if (adapter == null)
                    Console.WriteLine("yyy adapter jest nullem");

                emailListView.ItemClick += (object sender, AdapterView.ItemClickEventArgs ea) =>
                {
                    String[] email = { emails[ea.Position] };

                    var dialog = ProgressDialog.Show(this, "Prosze czekac", "Weryfikacja danych", true);

                    new Thread(() =>
                    {
                    TwoTimes:
                        try
                        {
                            NetcampWebProxy.CheckIfUserIsRegistredResult result = proxy.CheckIfUserIsRegistred(email, DaysManager.GetLastDay().link);

                            Console.WriteLine("yyy Czek zakonczony");
                            if (result.confirmed)
                            {
                                var prefs = GetSharedPreferences("NetcampApp", 0);
                                var prefsEditor = prefs.Edit();
                                prefsEditor.PutString("Email", result.mail);
                                prefsEditor.PutBoolean("Donation", result.paidDonation);
                                prefsEditor.PutInt("CurrentStep", 2);
                                prefsEditor.PutString("Name", result.username);
                                prefsEditor.Commit();
                                var intent = new Intent(this, typeof(NetcampCountTheDistance));

                                StartActivity(intent);
                                Finish();
                            }
                            else
                                RunOnUiThread(() =>
                                    Toast.MakeText(this, "Brak adresu email na liscie zarejestrowanych", ToastLength.Long).Show());

                            RunOnUiThread(() => dialog.Hide());
                        }
                        catch (Exception e)
                        {
                            MWC.MWCApp.LogDebug(e);

                            if (tryForTheSecondTime)
                            {
                                tryForTheSecondTime = false;
                                goto TwoTimes;
                            }
                            else
                            {
                                RunOnUiThread(() =>
                                {
                                    dialog.Hide();
                                    MWC.NetcampAlerts.NoInternet(this, false);
                                });

                            }
                        }
                    }).Start();
                };

                var backButton = FindViewById<Button>(Resource.Id.backToConfiguration);

                backButton.Click += (s, e) =>
                    {
                        var intent = new Intent(this, typeof(NetcampHome));
                        StartActivity(intent);
                        Finish();
                    };
            }
            catch (Exception e)
            {
                MWCApp.LogDebug(e);
                NetcampAlerts.UnknownError(this);
            }

        }

        public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
        {
            if (keyCode == Keycode.Back)
            {
                Intent intent = new Intent(this, typeof(NetcampHome));
                StartActivity(intent);
                Finish();
            }

            return base.OnKeyDown(keyCode, e);
        }

        private void setFont(string path, List<TextView> tTV, TypefaceStyle Type)
        {
            AssetManager mgr;
            mgr = Assets;
            Typeface font = Typeface.CreateFromAsset(mgr, path);
            for (int i = 0; i < tTV.Count; i++)
            {
                tTV[i].SetTypeface(font, Type);
            }

        }
    }
}